package com.hx.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.hx.mybatisplus.generator.AutoGenerator;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName CodeGenerator
 * @Description //TODO
 * @Author WHX
 * @Date 2021/12/7 18:05
 **/
public class CodeGenerator {
    /**
     * 执行前，请修改自定义配置类：
     * CustomConfig
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        setGlobalConfig(mpg);

        // 数据源配置
        setDataSourceConfig(mpg);

        // 包配置
        PackageConfig pc = setPackageConfig(mpg);

        // 自定义配置:
        setInjectionConfig(mpg);

        // 配置模板
        setTemplateConfig(mpg);

        // 策略配置
        setStragyConfig(mpg, pc);

        // 最后手动创建configBuilder
        ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig());

        // 修改实体类默认引入的包：table.importPackages + 去掉service接口名称的前缀 "I"
        setImportPackages(configBuilder);
        // 修改xml生成路径到resources
        setPathInfo(mpg, configBuilder);

        mpg.setConfig(configBuilder);
        mpg.execute();
    }









    private static void setStragyConfig(AutoGenerator mpg, PackageConfig pc) {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setRestControllerStyle(true);
        // 下划线转驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 导出哪些表
        strategy.setInclude(CustomConfig.CHECK.TABLE_NAMES.split(","));
        strategy.setControllerMappingHyphenStyle(false);
        // superEntity字段过滤
        strategy.setSuperEntityColumns(CustomConfig.SUPER_ENTITY_COLUMS);
        mpg.setStrategy(strategy);
    }

    private static void setTemplateConfig(AutoGenerator mpg) {
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setEntity("templates/entity.java");
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
        templateConfig.setMapper("templates/mapper.java");
        templateConfig.setXml("templates/mapper.xml");
        templateConfig.setController("templates/controller.java");
        mpg.setTemplate(templateConfig);
        // 模板引擎
        mpg.setTemplateEngine(new VelocityTemplateEngine());
    }

    private static void setInjectionConfig(AutoGenerator mpg) {
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing  模板文件中可以从个map里取值
                Map<String, Object> map = new HashMap<>();
                // 自定义屬性注入： ${cfg.abc}
                map.put("abc", "testabc");
                map.put("idType", CustomConfig.MAPPER_ID_TYPE);
                this.setMap(map);
            }
        };

        mpg.setCfg(cfg);
    }

    private static void setDataSourceConfig(AutoGenerator mpg) {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://" + CustomConfig.CHECK.HOST +
                ":" + CustomConfig.CHECK.PORT +
                "/" + CustomConfig.CHECK.DB_NAME +
                "?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(CustomConfig.CHECK.USERNAME);
        dsc.setPassword(CustomConfig.CHECK.PASSWORD);
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
    }

    private static void setGlobalConfig(AutoGenerator mpg) {
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(CustomConfig.JAVA_PATH);
        gc.setAuthor(CustomConfig.AUTHOR);
        gc.setOpen(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        // 数据库时间类型 到 实体类时间类型 对应策略：只使用 java.util.date 代替
        gc.setDateType(DateType.ONLY_DATE);
        // 覆盖文件
        gc.setFileOverride(true);
        mpg.setGlobalConfig(gc);
    }

    private static void setPathInfo(AutoGenerator mpg, ConfigBuilder configBuilder) {
        Map<String, String> pathInfo = configBuilder.getPathInfo();
        pathInfo.put(ConstVal.XML_PATH, joinPath(CustomConfig.MAPPER_XML_PATH, mpg.getPackageInfo().getXml()));
    }

    private static void setImportPackages(ConfigBuilder configBuilder) {
        for (TableInfo tableInfo : configBuilder.getTableInfoList()) {
            Set<String> importPackages = tableInfo.getImportPackages();
            // 由于不需要@TableId 注解，也就不需要导入这两个包
            importPackages.remove(IdType.class.getCanonicalName());
            importPackages.remove(TableId.class.getCanonicalName());

            // 去掉service接口名称的前缀 "I"
            String serviceName = tableInfo.getServiceName();
            if (serviceName.startsWith("I")) tableInfo.setServiceName(serviceName.substring(1));
        }
    }

    private static PackageConfig setPackageConfig(AutoGenerator mpg) {
        PackageConfig pc = new PackageConfig();
        pc.setParent(CustomConfig.PACKGE);
        pc.setModuleName(CustomConfig.MODULENAME);
        pc.setEntity(CustomConfig.ENTITY);
        pc.setMapper(CustomConfig.MAPPER);
        pc.setXml(CustomConfig.XML);
        pc.setService(CustomConfig.SERVICE);
        pc.setServiceImpl(CustomConfig.SERVICEIMPL);
        pc.setController(CustomConfig.CONTROLLER);
        mpg.setPackageInfo(pc);
        return pc;
    }


    private static String joinPath(String parentDir, String packageName) {
        if (StringUtils.isBlank(parentDir)) {
            parentDir = System.getProperty(ConstVal.JAVA_TMPDIR);
        }
        if (!StringUtils.endsWith(parentDir, File.separator)) {
            parentDir += File.separator;
        }
        packageName = packageName.replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
        return parentDir + packageName;
    }

}
